import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/dv_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';

class DetailsValidateBloc implements BlocBase {
  StreamController<Object> _validateController = StreamController<Object>();
  StreamSink get validateDate => _validateController.sink;

  DetailsValidateBloc() {
    _validateController.stream.listen(validateData);
  }

  void validateData(data) {
    if (data is Map) {
      _validateTask(data);
    }
  }

  void _validateTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext).requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.COMMO_ISSHOP_URL, data: data, headers: {}, success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            DvEntity params = DvEntity.fromJson(result);
            if (BaseConstant.SUCESS == params.result) {
              // if (BaseConstant.ONLY_ZFB == params.remark) {
              //   eventBus.fire(ZfbShopEvent());
              // } else {
              eventBus.fire(ValidateNewShopEvent(params));
              // }
            } else if (BaseConstant.FAIL == params.result) {
              BotToast.showText(text: params.result);
            } else {
              BotToast.showText(text: params.result);
            }
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _validateController?.close();
  }
}
